package com.tma.internship.connectserver;

import java.io.InputStream;
import java.net.URLDecoder;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public abstract class ThreadContactServer<T> extends Thread implements ServiceCallback<T>{
	private List<NameValuePair> nameValuePairs;
	private String action;
	protected static final String charset = "UTF-8";
	public ThreadContactServer(List<NameValuePair> nameValuePairs,String action){
		super();
        this.nameValuePairs = nameValuePairs;
        this.action = action;
        	ServerInfo.httpclient = new DefaultHttpClient();
        ServerInfo.httppost = new HttpPost(ServerInfo.hostUrl+action);
	}
	public List<NameValuePair> getNameValuePair(){
		return nameValuePairs; 
	}
	public abstract void processReceiveData(InputStream in) throws Exception;
	@Override
	public void run() {
		// TODO Auto-generated method stub
		try {
            
            
            InputStream is = null;
            ServerInfo.httppost.setEntity(new UrlEncodedFormEntity(
                            nameValuePairs, charset));
            HttpResponse response = ServerInfo.httpclient
                            .execute(ServerInfo.httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
            processReceiveData(is);
//            StringBuffer stringBuffer = new StringBuffer();
//	        char ch;
//	        int c;
//	        while ((c = is.read()) != -1) {
//	              ch = (char) c;
//	              stringBuffer.append(ch);
//	        }
//	        result = new String(stringBuffer);
//	        result = URLDecoder.decode(result, charset);
//	        onSuccess(result);
	    } catch (Exception ex) {
	            onFailure(ex);
	    }
	}
}
